package com.xjrh.travel.data.apply.config.thread;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步线程配置
 *  <p>
 *      修复同一时间无法执行多个定时任务问题。@Scheduled默认是单线程的
 *  </p>
 *
 * @author snps
 * @create 2025-10-30 22:59
 * @describe
 **/
@Configuration
@EnableAsync
@Slf4j
public class AsyncScheduleTaskConfig {

    @Bean
    public Executor asyncTaskScheduler() {
        org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池数量，方法: 返回可用处理器的Java虚拟机的数量。
        int availableProcessors = Runtime.getRuntime().availableProcessors() * 2;
        executor.setCorePoolSize(availableProcessors);
        log.warn("AsyncTaskThreadExecutor-corePoolSize: {}", executor.getCorePoolSize());
        executor.setMaxPoolSize(availableProcessors * 2);
        log.warn("AsyncTaskThreadExecutor-maxPoolSize: {}", executor.getMaxPoolSize());
        executor.setQueueCapacity(20);
        executor.setThreadNamePrefix("AsyncTaskThread-");
        /**
         * 线程存活时间
         */
        executor.setKeepAliveSeconds(180);
        /**
         * 拒绝处理策略
         *      CallerRunsPolicy()：交由调用方线程运行，比如 main 线程。
         *      AbortPolicy()：直接抛出异常。
         *      DiscardPolicy()：直接丢弃。
         *      DiscardOldestPolicy()：丢弃队列中最老的任务。
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        executor.initialize();

        return executor;
    }


}